<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>App应用预览</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="__LAYUIADMIN__/res/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="__LAYUIADMIN__/res/adminui/dist/css/admin.css" media="all">
    <style>
        .admin-container {
            padding: 20px;
        }

        .layui-tab-content {
            padding: 20px 0;
        }

        .layui-form-item {
            margin-bottom: 25px;
        }

        .layui-upload-img {
            width: 100px;
            height: 100px;
            margin: 10px;
        }

        .layui-upload-list img {
            max-width: 300px;
            max-height: 200px;
        }

        .update-history-item {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #e6e6e6;
            border-radius: 5px;
            position: relative;
        }

        .update-history-item .remove-update {
            position: absolute;
            right: 10px;
            top: 10px;
        }

        .preview-item {
            display: inline-block;
            position: relative;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .preview-item img {
            width: 200px;
            height: 125px;
            object-fit: cover;
            border-radius: 5px;
        }

        .preview-item .remove-preview {
            position: absolute;
            right: 5px;
            top: 5px;
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            border-radius: 50%;
            cursor: pointer;
        }

        .app-info-container {
            border: 1px solid hsl(0, 0%, 90%);
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
    </style>
</head>

<body>

    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-header">App预览图片</div>
                    <div class="layui-card-body">
                        <form class="layui-form" lay-filter="appForm">
                            <!-- 预览图片 -->
                            <fieldset class="layui-elem-field">
                                <legend>应用预览图</legend>
                                <div class="layui-field-box">
                                    <div class="layui-form-item">
                                        <div class="layui-upload">
                                            <button type="button" class="layui-btn" id="preview-upload">上传预览图</button>
                                            <div class="layui-upload-list" id="preview-list">
                                                <div class="preview-container">
                                                    <div class="preview-items">
                                                        {volist name="images" id="img" key="index"}
                                                        <div class="preview-item">
                                                            <img src="{$img}" alt="预览图{$index}" class="preview-image">
                                                            <div class="remove-preview"><i
                                                                    class="layui-icon layui-icon-close"></i></div>
                                                            <input type="hidden" name="images[]" value="{$img}">
                                                        </div>
                                                        {/volist}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="layui-form-item layui-form-text">
                                        <label class="layui-form-label">预览说明</label>
                                        <div class="layui-input-block">
                                            <p class="layui-text">预览图建议尺寸为 800x500 像素，最多上传 6 张预览图</p>
                                        </div>
                                    </div>
                                </div>
                            </fieldset>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="demo2">确认保存</button>
                                </div>
                            </div>
                        </form>
                    </div>

                </div>
            </div>

        </div>
    </div>
    </div>

    <script src="__LAYUI__/layui.js"></script>
    <script>
        layui.use(function () {
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            var util = layui.util;
            var upload = layui.upload;
            $ = layui.$;
            // 图片预览功能
            var $articleImages = document.querySelectorAll('.preview-image');
            var images = [];

            // 收集所有图片URL
            $articleImages.forEach(function (img) {
                images.push({
                    src: img.src,
                    alt: img.alt
                });
            });

            // 为每张图片绑定点击事件
            $articleImages.forEach(function (img, index) {
                img.onclick = function () {
                    // 使用layer.photos进行图片预览
                    layer.photos({
                        photos: {
                            "title": "文章图片预览",
                            "id": "images",
                            "start": index,
                            "data": images
                        },
                        anim: 5 // 缩放动画效果
                    });
                };
            });
            // 预览图上传
            upload.render({
                elem: '#preview-upload',
                url: '/admin/system/uploadImg',
                field: 'images',
                multiple: true,
                before: function (obj) {
                    // 预读本地文件示例
                    obj.preview(function (index, file, result) {
                        var previewItem = $([
                            '<div class="preview-item">',
                            '<img clsas="preview-image" src="' + result + '" alt="' + file.name + '" >',
                            '<div class="remove-preview"><i class="layui-icon layui-icon-close"></i></div>',
                            '</div>'
                        ].join(''));

                        $('#preview-list .preview-items').append(previewItem);

                        // 删除预览图
                        previewItem.find('.remove-preview').on('click', function () {
                            previewItem.remove();
                        });
                    });
                },
                done: function (res) {
                    if (res.code == 0 || res.code == 200) { // 兼容两种成功状态码
                        // 获取图片链接，根据接口返回格式调整
                        var imgUrl;
                        if (res.data && res.data.src) {
                            imgUrl = res.data.src;
                        } else if (res.data && res.data.url) {
                            imgUrl = res.data.url;
                        } else if (res.url) {
                            imgUrl = res.url;
                        } else if (typeof res.data === 'string') {
                            imgUrl = res.data; // 如果data直接是字符串URL
                        }

                        // 上传成功后，为图片添加隐藏的input字段，包含图片链接
                        var lastItem = $('#preview-list .preview-item').last();

                        // 添加隐藏的input字段，用于提交表单时包含图片链接
                        lastItem.append('<input type="hidden" name="images[]" value="' + imgUrl + '">');

                        // 更新图片源为服务器返回的链接
                        lastItem.find('img').attr('src', imgUrl);

                        layer.msg('上传成功');
                        console.log('已添加图片链接:', imgUrl);
                    } else {
                        layer.msg('上传失败: ' + (res.msg || '未知错误'));
                    }
                },
                error: function () {
                    layer.msg('上传接口异常');
                }
            });

            // 绑定已有元素的删除事件
            $(document).on('click', '.remove-preview', function () {
                $(this).closest('.preview-item').remove();
            });

            // 表单提交
            form.on('submit(demo2)', function (data) {
                var field = data.field; // 获取表单字段值

                // 收集所有图片链接
                var images = [];
                $('.preview-item input[name="images[]"]').each(function () {
                    images.push($(this).val());
                });

                // 创建一个新的对象来保存提交数据
                var postData = {};

                // 先复制原有的字段数据（除了images[]）
                for (var key in field) {
                    if (!key.startsWith('images[')) {
                        postData[key] = field[key];
                    }
                }

                // 将图片链接作为单独的字段添加到postData中
                for (var i = 0; i < images.length; i++) {
                    postData['img' + (i + 1)] = images[i];
                }

                // 如果表单中有is_show字段，处理它
                if (field.is_show) {
                    postData.is_show = field.is_show == 'on' ? 1 : 0;
                }

                // 使用AJAX发送数据
                $.post('/admin/app/update/?conf=app_img', postData, function (res) {
                    if (res.code == 200) {
                        layer.msg('保存成功');
                    } else {
                        layer.msg(res.msg || '保存失败');
                    }
                }).fail(function () {
                    layer.msg('请求失败');
                });

                return false; // 阻止表单跳转
            });
        });
    </script>
</body>

</html>